package com.ijpay.controller.alipay;

import java.util.Map;

import com.alipay.api.domain.AlipayTradePagePayModel;
import com.alipay.api.domain.AlipayTradeWapPayModel;
import com.alipay.api.internal.util.AlipaySignature;
import com.ijpay.controller.IJPayConsts;
import com.ijpay.interceptor.AliPayApiInterceptor;
import com.ijpay.model.Alipay;
import com.ijpay.model.App;
import com.ijpay.service.AlipayService;
import com.jfinal.aop.Before;
import com.jfinal.aop.Clear;
import com.jfinal.core.Controller;
import com.jfinal.kit.JsonKit;
import com.jfinal.kit.LogKit;
import com.jpay.alipay.AliPayApi;
import com.jpay.ext.kit.StrKit;
import com.jpay.util.StringUtils;
import com.jpay.vo.AjaxResult;

/**
 * @Email javen205@126.com
 * @author Javen
 */
@Before(AliPayApiInterceptor.class)
public class AliPayController extends Controller {
	private AjaxResult result = new AjaxResult();
	AlipayService alipayService = new AlipayService();

	@Clear
	public void index() {
		renderText("欢迎使用IJPay 中的支付宝支付 -By Javen");
	}

	/**
	 * Wap支付
	 */
	public void wapPay() {
		try {
			App app = getAttr("app");

			LogKit.info(JsonKit.toJson(app));

			String body = "我是测试数据-By Javen";
			String subject = "Javen Wap支付测试";
			String totalAmount = getPara("money", "0");
			String passbackParams = "1";
			String notify_domain = app.getDomain();
			if (StrKit.isBlank(notify_domain)) {
				renderJson(result.addError("通知域名为空"));
			}
			String returnUrl = notify_domain + "/ijpay/alipay/return_url";
			String notifyUrl = notify_domain + "/ijpay/alipay/notify_url";

			AlipayTradeWapPayModel model = new AlipayTradeWapPayModel();
			model.setBody(body);
			model.setSubject(subject);
			model.setTotalAmount(totalAmount);
			model.setPassbackParams(passbackParams);
			String outTradeNo = StringUtils.getOutTradeNo();
			System.out.println("wap outTradeNo>" + outTradeNo);
			model.setOutTradeNo(outTradeNo);
			model.setProductCode("QUICK_WAP_PAY");

			AliPayApi.wapPay(getResponse(), model, returnUrl, notifyUrl);
		} catch (Exception e) {
			e.printStackTrace();
		}
		renderNull();
	}

	/**
	 * PC支付
	 */
	public void pcPay() {
		try {
			App app = getAttr("app");
			String totalAmount = "88.88";
			String outTradeNo = StringUtils.getOutTradeNo();
			LogKit.info("pc outTradeNo>" + outTradeNo);
			String notify_domain = app.getDomain();
			if (StrKit.isBlank(notify_domain)) {
				renderJson(result.addError("通知域名为空"));
			}
			String returnUrl = notify_domain + "/ijpay/alipay/return_url";
			String notifyUrl = notify_domain + "/ijpay/alipay/notify_url";
			AlipayTradePagePayModel model = new AlipayTradePagePayModel();

			model.setOutTradeNo(outTradeNo);
			model.setProductCode("FAST_INSTANT_TRADE_PAY");
			model.setTotalAmount(totalAmount);
			model.setSubject("Javen PC支付测试");
			model.setBody("Javen IJPay PC支付测试");
			// 花呗分期相关的设置
			/**
			 * 测试环境不支持花呗分期的测试 hb_fq_num代表花呗分期数，仅支持传入3、6、12，其他期数暂不支持，传入会报错；
			 * hb_fq_seller_percent代表卖家承担收费比例，商家承担手续费传入100，用户承担手续费传入0，仅支持传入100、0两种，其他比例暂不支持，传入会报错。
			 */
			// ExtendParams extendParams = new ExtendParams();
			// extendParams.setHbFqNum("3");
			// extendParams.setHbFqSellerPercent("0");
			// model.setExtendParams(extendParams);

			AliPayApi.tradePage(getResponse(), model, notifyUrl, returnUrl);
			renderNull();
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	@Clear
	public void return_url() {
		try {
			// 获取支付宝GET过来反馈信息
			Map<String, String> map = AliPayApi.toMap(getRequest());
			/*
			 * charset = UTF-8 out_trade_no = 010118073515148 method =
			 * alipay.trade.wap.pay.return total_amount = 1.00 sign =
			 * GszuSIyicJ2xnVGQD3oD7ZcC8zya+fEtamt7Luazc0hCzPIS+hgy0/
			 * c1nDAkVaPn7zdOeP7k9Jyt2ZBZclsccXf2xmrxWwAegnqWc1LVocj0XYmNep3CyfyHLmlLZxn7BsHL
			 * +o0p/QU2N40PQPCB8wIc8wBwtmD2/vTcVuZilGg9a6gUbs7n/
			 * fPfIFhRLSbUBmuXSGTem0KbVMgBD0Iv1brKXKRuj71o0k8efDJoANoiLWC72uPnFnrVx4fe6+
			 * X6LZVKXhKnR5AD03+s+pDzIoIFL3uO2HF6hhD1Rtj0A0tJXpHnvAGvY7Uvd0JGFQYhDkrH+
			 * nxQd8NT1Lu96oGLOQ== trade_no = 2018010121001004200200320876 auth_app_id =
			 * 2016102000727659 version = 1.0 sign_type = RSA2 app_id = 2016102000727659
			 * seller_id = 2088102180432465 timestamp = 2018-01-01 18:07:48
			 */

			for (Map.Entry<String, String> entry : map.entrySet()) {
				System.out.println(entry.getKey() + " = " + entry.getValue());
			}
			String appId = map.get("app_id");
			Alipay alipay = alipayService.getAlipayByAliPayAppId(appId);

			LogKit.error(JsonKit.toJson(alipay));

			if (alipay != null) {
				boolean verify_result = AlipaySignature.rsaCheckV1(map, alipay.getPublicKey(), IJPayConsts.CHARSET,
						IJPayConsts.SIGN_TYPE);
				if (verify_result) {// 验证成功
					// 请在这里加上商户的业务逻辑程序代码
					System.out.println("return_url 验证成功");
					renderText("success");
					return;
				}
			}
			System.out.println("return_url 验证失败");
			renderText("failure");
			return;
		} catch (Exception e) {
			e.printStackTrace();
			renderText("failure");
		}
	}

	@Clear
	public void notify_url() {
		try {
			// 获取支付宝POST过来反馈信息
			Map<String, String> params = AliPayApi.toMap(getRequest());
			/*
			 * gmt_create = 2018-01-01 18:07:45 charset = UTF-8 seller_email =
			 * nbuljj0108@sandbox.com subject = Javen Wap支付测试 sign =
			 * sgO/z7qFTO65gYevYG7l83niwP/
			 * hCnCNoHWVRWEczMrcTfcexWHpHde25EBlBOe8TxzYIHTbsNdI0Er+
			 * A42QCrLwQen1NnvtFZXVp8djmPTeucrWDAj6MZh8WK4XecR/
			 * pyHMBEz9tV9i9yfD9UzLjgWIwbpD9EV6fd2BGSU1aQrRGkT+EDW/
			 * dhuJszN7gqIdF7Ru24FJoOmRFS63vn/
			 * 067owT97TOpab4kL97Q8kBmqaJVNYieJk7lJYE4Bbi5OfjmEN6n/xKJOm9TbDSQ0zZUjiCogO+
			 * JQpCnZXXNiFcO5IvoeRE0SMNHJQuUWJ7qvuVg0PaR9UJyztVcGVtNhOdA== body = 我是测试数据-By
			 * Javen buyer_id = 2088102169474200 invoice_amount = 1.00 notify_id =
			 * 49725e021ed1182f65429d7cebbb1e6hjm fund_bill_list =
			 * [{"amount":"1.00","fundChannel":"ALIPAYACCOUNT"}] notify_type =
			 * trade_status_sync trade_status = TRADE_SUCCESS receipt_amount = 1.00 app_id =
			 * 2016102000727659 buyer_pay_amount = 1.00 sign_type = RSA2 seller_id =
			 * 2088102180432465 gmt_payment = 2018-01-01 18:07:46 notify_time = 2018-01-01
			 * 18:07:47 passback_params = 1 version = 1.0 out_trade_no = 010118073515148
			 * total_amount = 1.00 trade_no = 2018010121001004200200320876 auth_app_id =
			 * 2016102000727659 buyer_logon_id = abp***@sandbox.com point_amount = 0.00
			 */
			for (Map.Entry<String, String> entry : params.entrySet()) {
				System.out.println(entry.getKey() + " = " + entry.getValue());
			}
			String appId = params.get("app_id");
			Alipay alipay = alipayService.getAlipayByAliPayAppId(appId);
			LogKit.error(JsonKit.toJson(alipay));
			if (alipay != null) {
				boolean verify_result = AlipaySignature.rsaCheckV1(params, alipay.getPublicKey(), IJPayConsts.CHARSET,
						IJPayConsts.SIGN_TYPE);
				if (verify_result) {// 验证成功
					// 请在这里加上商户的业务逻辑程序代码 异步通知可能出现订单重复通知 需要做去重处理
					System.out.println("notify_url 验证成功succcess");
					renderText("success");
					return;
				}
			}
			System.out.println("notify_url 验证失败");
			renderText("failure");
			return;
		} catch (Exception e) {
			e.printStackTrace();
			renderText("failure");
		}
	}
}